
// 清理缓存
const storagePrefix = 'LC-'// 前缀

let userNo = localStorage.getItem(storagePrefix + 'userNo') || 'noUser'
// 缓存有效期cacheTime 单位秒
function localData (okey, value, cacheTime) {
  let key = ''
  if (okey === 'userNo') {
    // 更新userNo
    key = storagePrefix + okey
    if (value && userNo !== value) {
      userNo = value
      localStorage.setItem(key, value)
      // 清理上一个用户的缓存以及变更noUser
      for (let i = 0; i < localStorage.length; i++) {
        const key2 = localStorage.key(i) || ''
        if (key2.indexOf(storagePrefix) === 0) {
          // 数据变更
          if (key2.indexOf(storagePrefix + 'noUser') === 0) {
            localStorage.setItem(key2.replace(storagePrefix + 'noUser', storagePrefix + userNo), localStorage.getItem(key2))
          } else if (key !== key2 && key2.indexOf(storagePrefix + userNo) !== 0) {
            localStorage.removeItem(key2)
          }
        }
      }
    }
    return userNo
  } else {
    key = storagePrefix + userNo + '-' + okey
  }
  const storage = localStorage
  const getItemValue = function () {
    let data = storage.getItem(key)
    if (!data) {
      return data
    }
    // 不在有效期内
    if (/CT(\d+)=(\d+)$/.test(data)) {
      data = data.replace(/CT(\d+)=(\d+)$/, '')
      if (parseInt(RegExp.$1 * 1000) + parseInt(RegExp.$2) > new Date().getTime()) {
        storage.removeItem(key)
        return
      }
    }
    try {
      data = JSON.parse(data)
    } catch (e) {
      console.log(e.message)
    }
    return data
  }
  if (key && value === undefined) {
    return getItemValue()
  } else if (key && value === null) {
    // ios的时候，fix removeItem后，再马上getItem的时候，能获取到数据
    storage.setItem(key, '')
    storage.removeItem(key)
  } else {
    let data = JSON.stringify(value)
    if (cacheTime > 0) {
      data = data + 'CT' + cacheTime + '=' + new Date().getTime()
    }
    storage.setItem(key, data)
  }
}
export default localData
